package com.lzc.websocket;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.lzc.util.JwtUtil;
import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/tcp/channel/{jwt}")
public class WebSocketListener{

    public static Map<Long,Session> sessions = new ConcurrentHashMap<Long,Session>();

    @Setter
    private static ApplicationContext applicationContext;

    // 收到消息
    @OnMessage
    public void onMessage(String message){
        // json -> MessageCommand
        MessageCommand command = JSONUtil.toBean(message, MessageCommand.class);

        switch (command.getCode()){
            case 200:{
                // 私聊
                applicationContext.getBean(MessageHandler.class).singChat(command);
                break;
            }
            default:{
                break;
            }
        }

    }

    // 连接打开
    @OnOpen
    public void onOpen(Session session, @PathParam("jwt") String jwt){

        Long keyId = JwtUtil.getUid(jwt);
        if (keyId == null){
            return;
        }
        sessions.put(keyId,session);
        System.out.println("用户："+keyId+"已登录");
        System.out.println(sessions.keySet());
    }

    // 连接关闭
    @OnClose
    public void onClose(Session session){
        // 清楚session
        for (Map.Entry<Long, Session> entry : sessions.entrySet()) {
            if (entry.getValue() == session){
                sessions.remove(entry.getKey());
                break;
            }
        }
        System.out.println(sessions.keySet());

    }

    // 连接异常
    @OnError
    public void onError(Throwable throwable,Session session){
        System.out.println(session);

    }

}
